<?php

namespace app\api\controller;

use app\admin\model\Admin;
use app\admin\model\CustomerServiceAccount;
use app\admin\model\CustomerServiceAccountMiddle;
use app\admin\model\PartnerAdmin;
use app\admin\model\SmsConfig;
use app\api\model\PayConfig;
use sms\KmiMarketing;
use super\Http;
use think\Controller;
use think\Db;

class Test extends Controller
{
    private static $queue = "TEST_TASK";

    public function putTxt()
    {
        $list = Admin::select();
        var_dump($list);
        die();
//        $cacheKey = 'SET4_NEW_DB_TXT';
//        $user_id = Cache::store('redis')->get($cacheKey);
////        $user_id = 0;
//        $where = [
//            'create_time' => ['>', 1715788800],
//            'id' => ['>', $user_id]
//        ];
//        $list = \app\api\model\User::field('id,username')->where($where)->order('id', 'asc')
//            ->limit(0, 1000)->select();
//        if (empty($list)) {
//            return false;
//        }
//        $txt = '';
//        foreach ($list as $value) {
//
//            $txt .= '91' . $value['username'] . "\n";
//            $user_id = $value['id'];
//        }
//        $file = './example.txt';
//        $res = file_put_contents($file, $txt, FILE_APPEND);
//        if ($res) {
//            Cache::store('redis')->set($cacheKey, $user_id, 0);
//        }
//        var_dump($res);
//        var_dump($user_id);
        die();
    }

    public function testblpay()
    {
//        //删除指定时间戳前的数据 sql
//        //DELETE FROM your_table WHERE date_column < 1710854225;
//        $mer_no = '793686';
//        $key = '1OgOh0vBzYk17EVLV2eJBiqRd32x6499';
//        $pay = new \pay\blsoportepay\Pay($mer_no, $key);
//        $data = [
//            'out_trade_no' => 'TDC20231211121538787731432myAA',
//            'amount_money' => 1000.00,
//        ];
//        $res = $pay->payment($data);
//        var_dump($res);
        die();
    }

    public function getip()
    {
        echo request()->ip();
        die();
    }

    //失效客户禁止登录
    public function endLogin()
    {
        $where = [
            'is_pay_status' => 1,
            'status' => 1
        ];
        \app\api\model\User::update(['status' => 0], $where);
    }

    //定时写入
    public function setNewDb()
    {
//        $cacheKey = 'SET_NEW_DB_1';
//        $user_id = Cache::store('redis')->get($cacheKey);
////        $user_id = '';
//        if (empty($user_id)) {
//            $user_id = '613130';
//        }
//        $where = [
//            'id' => ['>', $user_id],
//            'is_pay' => 1
//        ];
//        $list = Db::name('user')->where($where)->order('id', 'asc')->limit(10)->select()->toArray();
//        $num = count($list);
//        //做容错处理  没有新用户的时候  不进行脚本
//        if (empty($num)) {
//            echo '无新用户';
//            die();
//        }
//        $user_id = $list[$num - 1]['id'];
//        Cache::store('redis')->set($cacheKey, $user_id, 0);
//
//        foreach ($list as $key => $value) {
//            //生成user插入数组
//            $userData = $value;
//            //查询用户对应的银行卡信息
//            $user_bank_info = Db::name('user_bank')->where(['user_id' => $value['id']])->find();
//            //查询用户对应的个人信息
//            $user_info = Db::name('user_info')->where(['user_id' => $value['id']])->select()->toArray();
//            //查询用户贷款订单信息
//            $loan_info = Db::name('loan_order')->where(['user_id' => $value['id']])->find();
//            //查询用户支付页面信息
//            $pay_view_info = Db::name('pay_view')->where(['user_id' => $value['id'], 'status' => 3])->select()->toArray();
//            //查询用户支付订单信息
//            $order_info = Db::name('order')->where(['user_id' => $value['id'], 'status' => 3])->select()->toArray();
//
//            //开始插入
//            Db::connect('database.database2')->name('user')->insert($userData);
//            if (!empty($user_bank_info)) {
//                //执行插入操作
//                Db::connect('database.database2')->name('user_bank')->insert($user_bank_info);
//
//            }
//            if (!empty($user_info)) {
//                //执行插入操作
//                Db::connect('database.database2')->name('user_info')->insertAll($user_info);
//            }
//            if (!empty($loan_info)) {
//                //执行插入操作
//                Db::connect('database.database2')->name('loan_order')->insert($loan_info);
//            }
//            if (!empty($pay_view_info)) {
//                //执行插入操作
//                Db::connect('database.database2')->name('pay_view')->insertAll($pay_view_info);
//            }
//            if (!empty($order_info)) {
//                //执行插入操作
//                Db::connect('database.database2')->name('order')->insertAll($order_info);
//            }
//        }
        die();
    }

    public function tatat()
    {
        $mer_no = 'M888012';
        $key = '9QeayDU5o872EvseMkDcYWgosQpzvYdA72WrmQqn5OecvWfif2r1uuTHXB8tvfYZzqoFATvP2ExdiK9CYoR4Js5YfPjgb5uEAW0ONewimXb4yknVUo5imy72MxSHByi9';
        $pay = new \pay\ppay\Pay($mer_no, $key);
        $data = [
            'out_trade_no' => 'TDY20231211121538787731449myAA',
            'amount_money' => 1000,
        ];
        $res = $pay->payment($data);
        var_dump($res);
        die();
        //测试mo支付
//        $mer_no = '10117';
//        $key = 'ujd1wcrxtqidy3xhbtkf9ndswils8l7c';
//        $pay = new \pay\mopay\Pay($mer_no, $key);
//        $data = [
//            'out_trade_no' => 'TDC20231211121538787731459myAA',
//            'amount_money' => 1000,
//        ];
//        $pay->payment($data);
//        echo request()->ip();
//        die();
        //测试ad上报
//        $send = new SendS2sAdjust();
//        $res = $send->sendAdjust('682858', 'income', '17', ['amount_money' => 2500]);
//        die();
        //修正错误数据
        $where = [
            'app_base_id' => 18,
        ];
        $loanList = \app\api\model\LoanOrder::where($where)->select();
        foreach ($loanList as $key => $value) {
            $userInfo = \app\api\model\User::get($value['user_id']);
            $accountMiddleInfo = \app\api\model\CustomerServiceAccountMiddle::get($userInfo['customer_service_account_middle_id']);
            $accountInfo = CustomerServiceAccount::get($accountMiddleInfo['customer_service_account_id']);
            $info = [
                'partner_id' => $accountInfo['partner_id'],
                'customer_service_group_id' => $accountInfo['customer_service_group_id'],
                'customer_service_personnel_id' => $accountInfo['customer_service_personnel_id'],
            ];
            \app\api\model\LoanOrder::update($info, ['id' => $value['id']]);
        }
        die();
//        $page = $this->request->get("page", '1');
//        $size = 1000;
//        $where = [
////            'create_time' => ['<', 1692720000],
//            'app_base_id' => 16,
//        ];
//        $list = User::field('id,username,mobilResetGooglee,app_base_id')
//            ->where($where)
//            ->page($page, $size)
//            ->order('id', 'asc')
//            ->select()
//            ->toArray();
//        foreach ($list as $value) {
//            //检查用户是否在其他app注册过
//            $oldWhere = [
//                'username' => $value['username'],
//                'app_base_id' => ['neq', $value['app_base_id']]
//            ];
//            $oldUser = \app\admin\model\User::field('id,is_pay')->where($oldWhere)->select()->toArray();
//            $upData['old_status'] = 1;
//            if (!empty($oldUser)) {
//                $upData['old_status'] = 2;
//                foreach ($oldUser as $v) {
//                    if ($v['is_pay'] == 1) {
//                        $upData['old_status'] = 3;
//                    }
//                }
//            }
//            User::update($upData, ['id' => $value['id']]);
//        }
//
//        echo $page;
//        echo count($list);
    }

    public function subUnit()
    {
        $username = $this->request->get("username");
        $url = 'https://dk.hujl55.com/index/verphone/addphone.jsp?phone=' . $username;
        Http::get($url);
        echo "上报成功";
    }


    public function CostAuto()
    {
        $year = $this->request->get("year");
        $month = $this->request->get("month");
        $cost = $this->request->get("cost");
        $appid = $this->request->get("appid", 14);
        if (empty($cost)) {
            $this->error('成本不能为空');
        }
        if (empty($year)) {
            $this->error('年份错误');
        }
        if (empty($month)) {
            $this->error('月份错误');
        }
        $this->model = new \app\admin\model\Cost();
        $daysCount = date('t', mktime(0, 0, 0, $month, 1, $year));
        for ($day = 1; $day <= $daysCount; $day++) {
            $date = date(
                'Y-m-d',
                mktime(0, 0, 0, $month, $day, $year)
            );
            $time = strtotime($date);
            $res = $this->model->where([
                'app_base_id' => $appid,
                'time' => $time
            ])
                ->find();
            if (!empty($res)) {
                echo "添加失败,该日已添加成本!";
                die();
            }
            $params = [
                'app_base_id' => $appid,
                'cost' => $cost,
                'time' => $time,
                'admin_id' => 14
            ];
            $res = $this->model->create($params);
            echo $date . "成本 " . $cost . "添加成功" . "<br/>";
            //执行成本添加
        }
        die();
    }

    //补充上报事件
    public function supplementEscalation()
    {
        //统计 注册数 今日用户提交信息数   下放额度数  申请贷款审核失败数  用户安装数量
        $startOpenTime = $this->request->get('start_time', date('Y-m-d', time()));
        $endOpenTime = $this->request->get('end_time', date('Y-m-d', time()));
        $startOpenTime = strtotime($startOpenTime . '00:00:00');//格式化开始时间
        $endOpenTime = strtotime($endOpenTime . '23:59:59');//格式化结束时间
        $distributionUserWhere['create_time'] = ['between', [$startOpenTime, $endOpenTime]];
        $regInfoWhere = [
            'app_base_id' => 15,
            'create_time' => ['between', [$startOpenTime, $endOpenTime]],
//            'current_status' =>
        ];
        //获取注册用户数量
        $reg_user_num = \app\api\model\User::where($regInfoWhere)->count('id');
        echo "注册用户数量 :" . $reg_user_num;
        echo "<br />";
        $subInfoWhere = [
            'app_base_id' => 15,
            'create_time' => ['between', [$startOpenTime, $endOpenTime]],
            'current_status' => ['>', 7]
        ];
        $sub_user_num = \app\api\model\User::where($subInfoWhere)->count('id');
        echo "提交用户信息数量 :" . $sub_user_num . "  占比 :" . round(($sub_user_num / $reg_user_num) * 100, 2) . "%";
        echo "<br />";
        //获取下放额度数量
        $quotaWhere = [
            'app_base_id' => 15,
            'create_time' => ['between', [$startOpenTime, $endOpenTime]],
            'current_status' => ['>', 20]
        ];
        $quota_user_num = \app\api\model\User::where($quotaWhere)->count('id');
        echo "已获取额度数量 :" . $quota_user_num . "  占比 :" . round(($quota_user_num / $reg_user_num) * 100, 2) . "%";
        echo "<br />";
        //获取申请贷款数量
        $loanWhere = [
            'app_base_id' => 15,
            'create_time' => ['between', [$startOpenTime, $endOpenTime]],
            'current_status' => ['>', 23]
        ];
        $loan_user_num = \app\api\model\User::where($loanWhere)->count('id');
        echo "提交贷款申请用户数量 :" . $loan_user_num . "  占比 :" . round(($loan_user_num / $reg_user_num) * 100, 2) . "%";
        echo "<br />";
        //获取付过款的用户数量
        $payWhere = [
            'app_base_id' => 15,
            'create_time' => ['between', [$startOpenTime, $endOpenTime]],
            'is_pay' => 1
        ];
        $pay_user_num = \app\api\model\User::where($payWhere)->count('id');
        echo "付费用户数量 :" . $pay_user_num . "  占比 :" . round(($pay_user_num / $reg_user_num) * 100, 2) . "%";
        echo "<br />";
        //获取会员的用户数量
        $vipWhere = [
            'app_base_id' => 15,
            'create_time' => ['between', [$startOpenTime, $endOpenTime]],
            'member_config_id' => 1
        ];
        $vip_user_num = \app\api\model\User::where($vipWhere)->count('id');
        echo "会员用户数量 :" . $vip_user_num . "  占比 :" . round(($vip_user_num / $reg_user_num) * 100, 2) . "%";
        echo "<br />";
//        $distributionUser = new Distributionuser();
//        $accountMiddleId = $distributionUser->DistributionUserPartner(15);
//        var_dump($accountMiddleId);
//        die();
//        $params['amount_money'] = 150000;
//        var_dump($params['amount_money']);
//        //计算贷款金额是否是以万为单位的整数
//        $amountMoneyRem = $params['amount_money'] / 10000;
//        var_dump($amountMoneyRem);
//        var_dump(is_numeric($amountMoneyRem));
//        //如果不是整数,则向上取整
//        if (strpos($amountMoneyRem, '.') !== false) {
//            $amountMoneyRem = ceil($amountMoneyRem);
//            //取整后计算贷款金额
//            $params['amount_money'] = $amountMoneyRem * 10000;
//        }
//        var_dump($params['amount_money']);
//        die();
//        $time = '1667836800';
//        $offset = 800;
//        $user_list = User::field('id,app_base_id,username,channel')->where(['id' => ['>', 3275]])->order('id', 'desc')->limit($offset, '50')->select();
//
//        $sendS2sAdjust = new SendS2sAdjust();
//        foreach ($user_list as $key => $value) {
////            Adjustqueue::dispatch($value['id'], $value['pay_view_id']);
//            $equipment = UserEquipment::get(['user_id' => $value['id']]);
//            if (!empty($equipment['gps_adid'])) {
//                $sendS2sAdjust->sendAdjust($value['id'], 'reg', $value['app_base_id'], [], ['phone' => $value['username'], 'source' => $value['channel']]);
//            }
//            Log::info('adjust的注册事件用户id----' . $value['id']);
//            echo $value['id'] . "\n";
//        }
//        echo '脚本完成' . count($user_list);
    }

    /**
     * 重置客服谷歌验证码
     */
    public function ResetGoogle()
    {
        $params = request()->post();
        $user_name = $params['user_name'];
        $info = PartnerAdmin::where([
            'username' => $user_name
        ])
            ->find();
        $res = PartnerAdmin::update([
            'is_bind_google' => 0,
            'google_secret_key' => '',
            'token' => null,
        ], ['id' => $info['id']]);
        var_dump($res);
        die();
    }

    /**
     * 跨人员转移用户
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function Transfers()
    {
        //跨人员转移用户
//        $params = request()->post();
        $old_username = '917578958353';
        $new_username = '917635095634';
        $oldInfo = \app\admin\model\CustomerServiceAccount::where('username', '=', $old_username)->where('is_del', '=', 0)->find();
        if (empty($oldInfo)) {
            echo "老账户错误";
            die();
        }
        $oldMId = CustomerServiceAccountMiddle::where([
            'customer_service_account_id' => $oldInfo['id']
        ])->find();
        if (empty($oldInfo)) {
            echo "老账户未查到中间表信息";
            die();
        }
        $newInfo = \app\admin\model\CustomerServiceAccount::where('username', '=', $new_username)->where('is_del', '=', 0)->find();
        if (empty($oldInfo)) {
            echo "新账户错误";
            die();
        }
        $newMId = CustomerServiceAccountMiddle::where([
            'customer_service_account_id' => $newInfo['id']
        ])->find();
        if (empty($oldInfo)) {
            echo "新账户未查到中间表信息";
            die();
        }
        $count = \app\admin\model\User::where(['customer_service_account_middle_id' => $oldMId['id']])->count('id');
        if (empty($count)) {
            echo "旧账号无转移用户";
            die();
        }
        //转移成功后 所有用户的提示横幅字段打开
        $res = \app\admin\model\User::update(['is_show_contact_kf' => 1, 'is_remind_contact_kf' => 1, 'customer_service_account_middle_id' => $newMId['id']], ['customer_service_account_middle_id' => $oldMId['id']]);

        echo $res;
        die();
    }


    //测试发送营销短信
    public function testKmi()
    {
        $params = request()->post();
        if (empty($params['username'])) {
            echo 'username缺失!';
            die();
        }
        $kmi = new KmiMarketing();
        $res = $kmi->sendMsg($params['username'], 50000, 'https://www.smartloanapps.com');
        var_dump($res);
        die();
    }

    //测试后台管理订单查询功能
    public function test()
    {
        $params = request()->post();
        if (empty($params['out_trade_no'])) {
            echo 'out_trade_no缺失!';
            die();
        }
        $payConfigInfo = PayConfig::get(29);
        $payConfigKey = unserialize($payConfigInfo['configjson']);
        $payConfigKey = json_decode($payConfigKey, true);
        $payConfigKey = array_values($payConfigKey)[0];
        $pay = new \pay\goldpay\Pay($payConfigKey['appId'], $payConfigKey['appKey']);
        dump($pay->queryOrder($params));
    }

    public function rand($len = 10)
    {
        $chars = '0123456789';
        $string = time();
        for (; $len >= 1; $len--) {
            $position = rand() % strlen($chars);
            $position2 = rand() % strlen($string);
            $string = substr_replace($string, substr($chars, $position, 1), $position2, 0);
        }

        return $string;
    }

    //测试短信功能
    public function testKmiSend()
    {
        $params = $this->request->post();
        $phone = $params['phone'];
        $info = SmsConfig::getSmsIdByType(1);
        $smsClassName = '\sms\\' . $info['name'];
        $smsClass = new $smsClassName();
        $code = rand(100000, 999999);
        $smsData = $smsClass->sendMsg($phone, '1' . $code);
        var_dump($smsData);
        die();

    }

    public function aaa()
    {
        $states = array(
            "Andhra Pradesh", "Arunachal Pradesh", "Assam", "Bihar", "Chhattisgarh",
            "Goa", "Gujarat", "Haryana", "Himachal Pradesh", "Jharkhand",
            "Karnataka", "Kerala", "Madhya Pradesh", "Maharashtra", "Manipur",
            "Meghalaya", "Mizoram", "Nagaland", "Odisha", "Punjab",
            "Rajasthan", "Sikkim", "Tamil Nadu", "Telangana", "Tripura",
            "Uttar Pradesh", "Uttarakhand", "West Bengal"
        );
        $cities = array(
            "Andhra Pradesh" => array("Visakhapatnam", "Vijayawada", "Guntur", "Nellore"),
            "Arunachal Pradesh" => array("Itanagar", "Naharlagun", "Pasighat", "Tawang"),
            "Assam" => array("Guwahati", "Silchar", "Dibrugarh", "Jorhat"),
            "Bihar" => array("Patna", "Gaya", "Bhagalpur", "Muzaffarpur"),
            "Chhattisgarh" => array("Raipur", "Bilaspur", "Durg", "Bhilai"),
            "Goa" => array("Panaji", "Margao", "Vasco da Gama", "Mapusa"),
            "Gujarat" => array("Ahmedabad", "Surat", "Vadodara", "Rajkot"),
            "Haryana" => array("Gurugram", "Faridabad", "Panipat", "Ambala"),
            "Himachal Pradesh" => array("Shimla", "Dharamshala", "Solan", "Mandi"),
            "Jharkhand" => array("Ranchi", "Jamshedpur", "Dhanbad", "Bokaro"),
            "Karnataka" => array("Bengaluru", "Mysuru", "Mangaluru", "Hubballi"),
            "Kerala" => array("Thiruvananthapuram", "Kochi", "Kozhikode", "Thrissur"),
            "Madhya Pradesh" => array("Bhopal", "Indore", "Gwalior", "Jabalpur"),
            "Maharashtra" => array("Mumbai", "Pune", "Nagpur", "Nashik"),
            "Manipur" => array("Imphal", "Thoubal", "Bishnupur", "Churachandpur"),
            "Meghalaya" => array("Shillong", "Tura", "Jowai", "Nongpoh"),
            "Mizoram" => array("Aizawl", "Lunglei", "Saiha", "Champhai"),
            "Nagaland" => array("Kohima", "Dimapur", "Mokokchung", "Tuensang"),
            "Odisha" => array("Bhubaneswar", "Cuttack", "Rourkela", "Puri"),
            "Punjab" => array("Chandigarh", "Ludhiana", "Amritsar", "Jalandhar"),
            "Rajasthan" => array("Jaipur", "Jodhpur", "Udaipur", "Kota"),
            "Sikkim" => array("Gangtok", "Geyzing", "Namchi", "Mangan"),
            "Tamil Nadu" => array("Chennai", "Coimbatore", "Madurai", "Tiruchirappalli"),
            "Telangana" => array("Hyderabad", "Warangal", "Nizamabad", "Khammam"),
            "Tripura" => array("Agartala", "Udaipur", "Dharmanagar", "Kailashahar"),
            "Uttar Pradesh" => array("Lucknow", "Kanpur", "Varanasi", "Agra"),
            "Uttarakhand" => array("Dehradun", "Haridwar", "Roorkee", "Haldwani"),
            "West Bengal" => array("Kolkata", "Darjeeling", "Siliguri", "Asansol")
        );

        foreach ($states as $k => $v) {
            $statesArr[$v] = 0;
        }
        foreach ($cities as $k => $v) {
            foreach ($v as $kk => $vv) {
                $citiesArr[$vv] = 0;
            }
        }

        $sex['男'] = $sex['女'] = 0;
        $data['<18'] = $data['19~25'] = $data['26~35'] = $data['36~45'] = $data['46~55'] = $data['>56'] = 0;
        // $join = [
        //     ['user_info b','a.id=b.user_id'],
        //     ['loan_order c','a.id=c.user_id'],
        // ];
        //$user = Db::name('user')->alias('a')->join($join)->field('a.id,a.loginip,b.info_json,c.pay_back_num')->where(['a.is_pay' => '1', 'b.type' => '34'])->select();
        $user = Db::name('user')->field('id')->where(['is_pay' => '1'])->select();

        foreach ($user as $k => $v) {
            $uinfo = Db::name('user_info')->field('info_json')->where(['type' => '34', 'user_id' => $v['id']])->find();
            $json = json_decode($uinfo['info_json'], true);
            $arr[$k]['sex'] = $json['sex'] ?? '';
            $arr[$k]['age'] = $json['age'] ?? '';
            $arr[$k]['current_address'] = $json['current_address'] ?? '';
            $arr[$k]['pay_back_num'] = $v['pay_back_num'] ?? '';
        }
        unset($user);
        foreach ($arr as $k => $v) {
            foreach ($statesArr as $kk => $vv) {
                if (strpos($v['current_address'], $kk)) {
                    $statesArr[$kk] += 1;
                }
            }
            foreach ($citiesArr as $kk => $vv) {
                if (strpos($v['current_address'], $kk)) {
                    $citiesArr[$kk] += 1;
                }
            }
            if ($v['sex'] == 'Male') {
                $sex['男'] += 1;
            }
            if ($v['sex'] == 'Female') {
                $sex['女'] += 1;
            }
            if ($v['age'] <= 18) {
                $data['<18'] += 1;
            }
            if ($v['age'] > 18 && $v['age'] < 26) {
                $data['19~25'] += 1;
            }
            if ($v['age'] > 25 && $v['age'] < 36) {
                $data['26~35'] += 1;
            }
            if ($v['age'] > 35 && $v['age'] < 46) {
                $data['36~45'] += 1;
            }
            if ($v['age'] > 45 && $v['age'] < 56) {
                $data['46~55'] += 1;
            }
            if ($v['age'] > 56) {
                $data['>56'] += 1;
            }
        }
        unset($arr);

        arsort($statesArr);
        arsort($data);
        arsort($sex);
        arsort($citiesArr);

        echo '----------邦数据从高到低----------<br/>';
        foreach ($statesArr as $k => $v) {
            echo $k . ' :' . $v . '人<br/>';
        }
        echo '----------城市数据从高到低----------<br/>';
        foreach ($citiesArr as $k => $v) {
            echo $k . ' :' . $v . '人<br/>';
        }
        echo '----------性别数据从高到低----------<br/>';
        foreach ($sex as $k => $v) {
            echo $k . ' :' . $v . '人<br/>';
        }
        echo '----------年龄段数据从高到低----------<br/>';
        foreach ($data as $k => $v) {
            echo $k . ' :' . $v . '人<br/>';
        }
    }
}